package cn.zzq.userscenter.springmvc.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.zzq.userscenter.auth.pojo.AMenu;
import cn.zzq.userscenter.auth.pojo.ARoleMenu;
import cn.zzq.userscenter.auth.service.IAuthService;
import cn.zzq.userscenter.common.util.ConstatFinalUtil;
import cn.zzq.userscenter.users.pojo.AAdmins;


@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter
{
	@Resource
	private IAuthService authService;
	/**
	 * 登录拦截器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		String info = "";
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		//判断用户是否登录
		if(admins == null ){
			/**
			 * 未登录访问登陆后的页面时
			 * 会客户端跳转登录页面
			 */
			/*非法访问，请登录后再操作*/
			info = ConstatFinalUtil.INFO_JSON.getString("8");
			session.setAttribute("info", info);
			/*客户端跳转登录页面*/
			response.sendRedirect(request.getContextPath()+"/login.htm");
			return false;
		}
		
		//权限验证
		String currentUrl = request.getRequestURL()+"";
		//System.out.println("AuthInterceptor.preHandle(url:)"+request.getRequestURL());
		//System.out.println("AuthInterceptor.preHandle(uri:)"+request.getRequestURI());
		//查询当前用户的的角色，以及该角色的所有权限
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("roleId", admins.getRoleId());
		Map<String,Object> resultMap = this.authService.findCondListRoleMenuService(null, condMap);
		List<ARoleMenu> roleMenuList = (List<ARoleMenu>) resultMap.get("list");
		
		//循环验证是否有该url的访问权限
		for (Iterator iterator = roleMenuList.iterator(); iterator.hasNext();)
		{
			ARoleMenu roleMenu = (ARoleMenu) iterator.next();
			ConstatFinalUtil.SYS_LOGGER.info("cutUrl:{},url:{}",request.getRequestURL(),roleMenu.getMenu().getUrl()); 
			//判断是否有权限
			if(currentUrl.indexOf(roleMenu.getMenu().getUrl()) != -1){
				return true;
			}
		}
		
		//没有权限，跳转到error.jsp
		response.sendRedirect(request.getContextPath()+"/info/error.jsp");
		return false;
	}
	
}
